<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 信息提示区域 -->
      <el-alert
        title="编辑商品信息"
        type="info"
        show-icon
        center
        :closable="false">
      </el-alert>

      <!-- 进度条区域 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px"
        label-position='top'>
        <el-tabs v-model="activeIndex" :tab-position="'left'">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="editForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="editForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="editForm.goods_number" type="number"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="(item) in manyTableData" :key="item.attr_id" :label="item.attr_name">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox size="mini" border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传区域 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="picList"
              list-type="picture"
              :headers="headerObj">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor
              v-model="editForm.goods_introduce">
            </quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btnEdit" @click="edit">保存</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

     <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="50%">
      <img :src="previewPath" alt="预览图片" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    return {
      activeIndex: '0',
      // 商品 id
      id: '',
      // 编辑表单数据对象
      editForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      // 编辑表单的校验规则对象
      editFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 商品参数数据
      manyTableData: [],
      // 商品属性数据
      onlyTableData: [],
      // 上传图片的 url 地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的 headers 请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览地址
      previewPath: '',
      // 控制图片预览对话框的显示和隐藏
      previewVisible: false,
      picList: []

    }
  },
  created() {
    this.getGoodsInfo()
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    $route: 'getGoodsInfo'
  },
  methods: {
    // 获取商品数据
    async getGoodsInfo() {
      // console.log(this.$route.query.id)
      this.id = this.$route.query.id
      // 获取数据
      const { data: res } = await this.$http.get('goods/' + this.id)
      if (res.meta.status !== 200) {
        this.$router.push('/goods')
        return this.$message.error('获取商品信息失败!')
      }
      // 将动态参数的值由字符串转成数组
      res.data.attrs.forEach(item => {
        if (item.attr_sel === 'many') {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          this.manyTableData.push(item)
        } else if (item.attr_sel === 'only') {
          this.onlyTableData.push(item)
        }
      })
      // console.log(this.manyTableData)
      // console.log(this.onlyTableData)
      // 处理图片列表
      this.picList = []
      res.data.pics.forEach(item => {
        const picInfo = { name: item.pics_id, url: item.pics_big_url }
        this.picList.push(picInfo)
      })
      console.log(this.picList)
      this.editForm = res.data
      console.log(this.editForm)
    },
    // 处理图片预览事件
    handlePreview(file) {
      console.log(file)
      // 获取图片访问地址
      this.previewPath = file.url
      this.previewVisible = true
    },
    // 处理移除图片操作
    handleRemove(file) {
      console.log(file)
      // 有老图片和新图片两种情况
      // 新图片
      if (file.response) {
        // 获取要移除图片的临时路径
        const tmpPath = file.response.data.tmp_path
        // 从上传表单中找到要移除图片索引值
        const index = this.editForm.pics.findIndex(x => x.pic === tmpPath)
        // 从上传表单中移除该图片对应的对象
        this.editForm.pics.splice(index, 1)
      } else if (file.url) {
        const index = this.editForm.pics.findIndex(x => x.pics_big_url === file.url)
        this.editForm.pics.splice(index, 1)
      }
      console.log(this.editForm.pics)
    },
    // 处理图片成功上传后回调
    handleSuccess(response) {
      console.log(response)
      // 拼接得到一个图片信息对象{pic:xxx}
      const picInfo = { pic: response.data.tmp_path }
      // 将拼接得到的对象添加到新增商品表单中 pics 字段
      this.editForm.pics.push(picInfo)
    },
    // 添加商品
    edit() {
      console.log(this.editForm)
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项!')

        // 处理动态参数
        this.editForm.attrs = []
        this.manyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.editForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.editForm.attrs.push(newInfo)
        })

        // 发起请求
        const { data: res } = await this.$http.put('goods/' + this.id, this.editForm)

        if (res.meta.status !== 200) {
          return this.$message.error('修改商品失败!')
        }

        this.$message.success('修改商品成功!')
        // 跳转到商品列表页面
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.previewImg{
  width: 100%;
}
.btnEdit{
  margin-top: 15px;
}
</style>
